#include "timeset.h"
#include "ui_timeset.h"
#include <QDebug>
#include <cstdlib>
#include "msgbox.h"
#include "clockmanager.h"
#include "userlogger.h"

TimeSet::TimeSet(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TimeSet)
{
    ui->setupUi(this);
    bdf = BllDataFlow::getInstance();

    connect(bdf, &BllDataFlow::retranslateUiSignal, this, &TimeSet::retranslateUiSlot);
    connect(bdf, &BllDataFlow::selectDateTimePickerSignal, this, &TimeSet::changeDateTime);
    connect(bdf, &BllDataFlow::setCurrentTimeSignal, this, &TimeSet::setCurrentTimeSlot);
    setShadow({ui->widget_2,ui->widget_3});

    timePicker = new DateTimePicker(nullptr, DateTimeType::Time, "timeset_timepicker");
    datePicker = new DateTimePicker(nullptr, DateTimeType::Date, "timeset_datepicker");

    if (windowWidth >= 1280) {
        ui->btnOK->setMinimumSize(280,90);
        ui->widget_2->setMinimumSize(250, 70);
        ui->widget_3->setMinimumSize(250, 70);
        ui->timeEdit->setGeometry(0,0,250,70);
        ui->dateEdit->setGeometry(0,0,250,70);
        ui->btnTimeEdit->setGeometry(0,0,250,70);
        ui->btnDateEdit->setGeometry(0,0,250,70);
        ui->label->setGeometry(198,18,34,34);
    }
}

TimeSet::~TimeSet()
{
    delete ui;
}

void TimeSet::on_btnOK_clicked()
{
    ui->btnOK->setEnabled(false);
    QDate date =ui->dateEdit->date();
    QTime time = ui->timeEdit->time();
    QString dateTimeStr = QDateTime(date, time).toString(FMT_S);
    QString currentDateTime = QDateTime::currentDateTime().toString(FMT_S);
    bool ret = setSystemTime(dateTimeStr);
    QString message = ret ? tr("datetime modify OK.") : tr("datetime modify Fail.");
    if (ret)
    {
        UserLogger::log(tr("modify datetime: from %1 to %2.").arg(currentDateTime).arg(dateTimeStr));
    }
    else
    {
        UserLogger::log(message);
    }

    MsgBox::information(this, tr("Tips"), message);
    ui->btnOK->setEnabled(true);
}

void TimeSet::retranslateUiSlot()
{
    ui->retranslateUi(this);
}

bool TimeSet::setSystemTime(const QString &datetime)
{
    return ClockManager::setDateTime(datetime);
}

void TimeSet::on_btnDateEdit_clicked()
{
    datePicker->show();
}

void TimeSet::setCurrentTimeSlot(int type)
{
    if(TimeSetType::SET_TIME == type)
    {
        QDateTime dateTime = QDateTime::currentDateTime();
        ui->dateEdit->setDate(dateTime.date());
        ui->timeEdit->setTime(dateTime.time());
    }
}

void TimeSet::on_btnTimeEdit_clicked()
{
    timePicker->show();
}

void TimeSet::changeDateTime(QDateTime dateTime, QString whatsThis)
{
    if (whatsThis == "timeset_datepicker") {
        ui->dateEdit->setDate(dateTime.date());
    } else if (whatsThis == "timeset_timepicker") {
        ui->timeEdit->setTime(dateTime.time());
    }
}
